import os
from flask import Flask
from flask_cors import CORS
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

def create_app(config_name=None):
    """创建Flask应用实例"""
    app = Flask(__name__)
    
    # 加载配置
    if config_name is None:
        config_name = os.environ.get('FLASK_ENV', 'development')
    
    try:
        from config.config import config
        app.config.from_object(config[config_name])
    except ImportError:
        # 如果没有config文件，使用默认配置
        app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY') or 'dev-secret-key'
        app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL') or 'sqlite:///smart_apitester.db'
        app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    
    # 初始化扩展
    db.init_app(app)
    CORS(app)
    migrate = Migrate(app, db)
    
    # 注册蓝图
    from app.api import api_bp
    
    app.register_blueprint(api_bp, url_prefix='/api')
    
    # 创建必要的文件夹
    if hasattr(app.config, 'UPLOAD_FOLDER'):
        os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
    
    # 创建日志文件夹
    log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logs')
    os.makedirs(log_dir, exist_ok=True)
    
    return app